package com.fzsf.drawingboard.ui

import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.WindowManager
import com.fzsf.drawingboard.R
import com.fzsf.drawingboard.app.MyApplication
import com.fzsf.drawingboard.bluetooth.FZWritingPadConstant
import com.fzsf.drawingboard.bluetooth.SimpleFZWritingPadCallBackListener
import com.fzsf.drawingboard.permission.EasyPermission
import com.fzsf.drawingboard.permission.PermissionResultCallback
import com.fzsf.drawingboard.utils.BlueToothUtils
import com.fzsf.drawingboard.utils.FileAccessor
import com.fzsf.drawingboard.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_main_kt.*

/**
 * Created by Taijl on 2018/1/29.
 * 使用Kotlin 创建MainActivity
 */
class MainActivityByKt : AppCompatActivity() {
    private val REQUEST_CODE_BLUETOOTH_ON = 1313
    private val REQUEST_CODE_GPS_ON = 1303
    private var easyPermission: EasyPermission? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_kt)
        initView()
    }

    /**
     * 初始化View(各个按钮的点击事件)
     */
    private fun initView() {
        btn_clear.setOnClickListener { clear() }
        btn_connect.setOnClickListener { connectDevice() }
        btn_disconnect.setOnClickListener { disConnect() }
        multi_writing.setOnClickListener {
            startActivity(Intent(MainActivityByKt@ this, MultiWritingActivity::class.java))
        }
    }

    private fun disConnect() {
        MyApplication.getInstance().writingPad?.let {
            it.disConnect()
            state_switch?.isChecked = false
        }
    }


    /**
     * 连接设备
     */
    private fun connectDevice() {
        val easyPermissionCallBack = object : PermissionResultCallback {
            override fun onPermissionGranted(grantedPermissions: List<String>) {
                checkAndConnect()
                FileAccessor.initFileAccess()
            }

            override fun onPermissionDenied(deniedPermissions: List<String>) {
                ToastUtil.showMessage("请授予应用蓝牙和定位权限，否则该功能不能正常使用！")
            }
        }

        easyPermission = with(EasyPermission.Builder(this, easyPermissionCallBack)) {
            permission(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)//申请那些权限
            rationalMessage("应用请求您授予部分权限")//想用户解释为什么需要这些权限
            deniedMessage("您没有授予我权限，部分功能将不能正常使用。你可以去设置页面重新授予权限")//用户仍然拒绝，引导用户去设置页面打开
            settingBtn(true)
            build()
        }

        easyPermission?.check()
    }

    /**
     * 检查并连接到设备
     */
    private fun checkAndConnect() =
            if (BlueToothUtils.isBleSupport()) {
                if (BlueToothUtils.isBlueToothEnable()) {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {//6.0以上
                        if (BlueToothUtils.isGpsEnable()) {
                            startActivity(Intent(this, ConnectActivity::class.java))
                        } else {
                            BlueToothUtils.turnOnGps(this, REQUEST_CODE_GPS_ON)
                        }
                    } else {
                        startActivity(Intent(this, ConnectActivity::class.java))
                    }
                } else {//没有开启蓝牙
                    BlueToothUtils.turnOnBluetooth(this, REQUEST_CODE_BLUETOOTH_ON)
                }
            } else {
                ToastUtil.showMessage("抱歉，您的设备不支持蓝牙，请更换设备")
            }

    /**
     * 清楚绘制面板内容
     */
    private fun clear() {
        drawing_board?.reSetBorad()
    }

    /**
     * Activity生命周期回调方法(启动)
     * 检查手写板的连接状态，设置手写板的回调
     */
    override fun onStart() {
        super.onStart()
        val writingPad = MyApplication.getInstance().writingPad
        if (null != writingPad) {
            drawing_board?.postDelayed({
                if (writingPad.definitePadType == FZWritingPadConstant.FZWritingPadType.TYPE_HYPEN) {
                    drawing_board?.setBoardSize(14800, 21000)
                } else {
                    drawing_board?.setBoardSize(9800, 13000)
                }
                state_switch?.isChecked = writingPad.connectState
                writingPad.switchWorkMode(FZWritingPadConstant.WorkMode.REAL_TIME)
                writingPad.setFZWritingPadCallBackListener(object : SimpleFZWritingPadCallBackListener() {
                    override fun onWorkModeChange(currentWorkMde: Int) {
                        state_switch?.isChecked = currentWorkMde == FZWritingPadConstant.WorkMode.REAL_TIME
                    }

                    override fun onWriting(x: Int, y: Int, z: Int, time: Long) {
                        runOnUiThread {
                            drawing_board?.writeByWritingPad(x, y, z)
                        }
                    }
                })
            }, 1000)
        }
    }

    /**
     * 页面跳转回调
     * 处理权限的申请
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_GPS_ON || requestCode == REQUEST_CODE_BLUETOOTH_ON) {
            checkAndConnect()
            return
        }
        easyPermission?.handleResult(requestCode, resultCode, data)
    }

}